local M = {}

function M.config()
  -- 确保图标正确加载
  require("nvim-web-devicons").setup({
    override = {},
    default = true
  })

  return {
    use_default_mappings = false,
    event_handlers = {
      {
        event = "neo_tree_buffer_enter",
        handler = function()
          vim.opt_local.signcolumn = "auto"
        end,
      },
    },
    window = {
      position = "left",
      width = 35,
      mapping_options = {
        noremap = true,
        nowait = true,
      },
      mappings = {
        ["u"] = "navigate_up",
        ["e"] = "toggle_preview",
        ["<tab>"] = "show_file_details",
        ["gl"] = "expand_all_nodes",
        ["gh"] = "close_all_nodes",
        ["i"] = "open",
        ["<cr>"] = "open",
        ["I"] = "open_vsplit",
        ["o"] = "toggle_node",
        ["O"] = "open_tabnew",
        ["n"] = "close_node",
        ["l"] = "navigate_up",
        ["yy"] = "copy",
        ["dd"] = "cut_to_clipboard",
        ["pp"] = "paste_from_clipboard",
        ["dD"] = "delete",
        ["a"] = "add",
        ["<S-n>"] = "add",
        ["m"] = "add_directory",
        ["r"] = "rename",
        ["."] = "toggle_hidden",
        ["zh"] = "toggle_hidden",
        ["R"] = "refresh",
        ["?"] = "show_help",
        ["q"] = "close_window",
        ["f"] = "fuzzy_finder",
        ["F"] = "fuzzy_finder_directory",
        ["["] = "prev_source",
        ["]"] = "next_source",
        ["[c"] = "prev_git_modified",
        ["]c"] = "next_git_modified",
      },
    },
  }
end

-- 定义一个函数来判断Neo-tree是否已经打开
local function is_neo_tree_open()
  local ok, win_info = pcall(vim.fn.getwininfo)
  if not ok then return false end

  for _, info in ipairs(win_info) do
    local bufnr = info.bufnr
    local ok, filetype = pcall(vim.api.nvim_buf_get_option, bufnr, "filetype")
    if ok and filetype == "neo-tree" then
      return true
    end
  end
  return false
end

-- 重新定义sv快捷键对应的操作
vim.keymap.set("n", "sv", function()
  local ok, _ = pcall(function()
    if is_neo_tree_open() then
      vim.cmd("Neotree close")
    else
      vim.cmd("Neotree focus reveal_force_cwd")
    end
  end)
  if not ok then
    vim.notify("Neo-tree 操作失败", vim.log.levels.WARN)
  end
end, { silent = true })

return M
